import { useState, useEffect, useRef, useImperativeHandle, forwardRef } from "react";
import { Dropdown, Button, Menu, Popover, Popconfirm, message, Switch, Space } from "antd";
import moment from "moment";
import TableRender from '@/components/TableRender';
import CommonLoading from "@/components/CommonLoading";
import ModifyRecordModal from "./ModifyRecordModal/index";
import {
	getTableDataOp,
	deleteEcStoreOp,
	updateSyncAfterSalesOrderStatus,
	updateSyncOrderGoods,
	updateSyncStockStatus,
	storeAuthClosed
} from "../service";
import { DownOutlined } from "@ant-design/icons";
import SetPickLabelModal from "./SetPickLabelModal";
import StoreSettingModal from "./StoreSettingModal";
import CloseStoreModal from "./CloseStoreModal";
import InventoryTipModal from "./InventoryTipModal";

const initPagination = {
	current: 1,
	total: 0,
	pageSize: 100,
	showQuickJumper: true,
	pageSizeOptions: [10, 20, 50, 100, 500]
};

const dateFormat = "YYYY-MM-DD HH:mm:ss";

//店铺状态
const storeStateMap = {
	1: "正常",
	2: "已到期",
	3: "已关闭",
	4: "授权失效"
};

//物流回传方式
const autoBackflowMap = {
	0: "默认回传",
	1: "获取单号后立即回流",
	2: "包装后回传",
	3: "备货后回传",
	4: "按平台发货时效回传"
};

//开关操作对应的接口
const operateSevice = {
	isSyncAfterSalesOrder: updateSyncAfterSalesOrderStatus,
	isSync: updateSyncOrderGoods,
	isSyncStock: updateSyncStockStatus
};

const TableContent = ({ query, updateKey, headerHeight, groupConfig, handleClick }, ref) => {
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState([]);
	const [pagination, setPagination] = useState(null); //分页数据
	const [recordData, setRecordData] = useState({}); //单行数据
	const [visible, setVisible] = useState(false); //弹窗的visible
	const [selectRowKeys, setSelectRowKeys] = useState([]);
	const [inventoryType, setinventoryType] = useState(false); //修改库存同步开关开闭还是开启

	const stageParams = useRef({});

	const columns = [
		{
			title: "序号",
			code: "index",
			lock: true,
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: "店铺编号",
			code: "id",
			width: 120
		},
		{
			title: "店铺",
			code: "systemStoreName",
			width: 120
		},
		{
			title: "所属平台",
			code: "typeName",
			width: 95
		},
		{
			title: "平台店铺",
			code: "storeName",
			width: 120
		},
		// {
		// 	title: "授权账号",
		// 	code: "payTime",
		// 	key: "payTime",
		// 	width: 95
		// },
		{
			title: "店铺状态",
			code: "storeState",
			width: 95,
			render: text => <span className={text == 1 ? "common-color10" : "common-color9"}>{storeStateMap[text]}</span>
		},
		{
			title: "物流回传方式",
			code: "autoBackflow",
			width: 120,
			render: (text, record) => (
				<div>
					{text == 4 ? (
						<Popover
							placement="bottomLeft"
							content={
								<div style={{ width: 200 }}>
									<p>按平台发货时效回传</p>
									<p>
										最晚发货时间：提前<span className="common-color10">{record?.inAdvanceBackflowTime}</span>小时
									</p>
									<p>
										自定义回传时间：<span className="common-color10">{record?.customBackflowTime}</span>小时
									</p>
								</div>
							}
						>
							<span>{autoBackflowMap[text]}</span>
						</Popover>
					) : (
						<span>{autoBackflowMap[text]}</span>
					)}
				</div>
			)
		},
		{
			title: "吊牌图片",
			code: "picInfoImage",
			width: 120,
			render: text => (
				<div>
					{text ? (
						<Popover content={<img src={text} style={{ width: 400 }} />}>
							<img src={text} style={{ width: "32px", height: "32px", borderRadius: "5px" }} />
						</Popover>
					) : (
						""
					)}
				</div>
			)
		},
		{
			title: "吊牌2图片",
			code: "goodCreditImage",
			width: 120,
			render: text => (
				<div>
					{text ? (
						<Popover content={<img src={text} style={{ width: 400 }} />}>
							<img src={text} style={{ width: "32px", height: "32px", borderRadius: "5px" }} />
						</Popover>
					) : (
						""
					)}
				</div>
			)
		},
		{
			title: "寄件地址",
			code: "addressVo",
			width: 200,
			render(text, record) {
				const str = text?.name + text?.mobPhone + text?.provinceName + text?.cityName + text?.areaName + text?.address;
				return <span>{str ? str : "-"}</span>;
			}
		},
		{
			title: "授权过期时间",
			code: "parseAuthExpireTime",
			width: 120
		},
		{
			title: "授权时间",
			code: "parseAuthLastTime",
			width: 95
		},
		{
			title: "更新时间",
			code: "updateTime",
			width: 95
		},
		{
			title: "同步库存",
			code: "isSyncStock",
			width: 95,
			render(text, record) {
				return (
					<Switch
						checkedChildren="开启"
						unCheckedChildren="关闭"
						checked={text == 1}
						size="large"
						// onClick={e => handleSwitch(e, record, "isSyncStock")}
						onClick={e => handleAsyncInventory(e, record)}
					/>
				);
			}
		},
		{
			title: "售后单下载",
			code: "isSyncAfterSalesOrder",
			width: 95,
			render(text, record) {
				return (
					<Switch
						checkedChildren="开启"
						unCheckedChildren="关闭"
						size="large"
						checked={text == 1}
						onClick={e => handleSwitch(e, record, "isSyncAfterSalesOrder")}
					/>
				);
			}
		},
		{
			title: "同步三方订单和商品数据",
			code: "isSync",
			width: 180,
			render(text, record) {
				return (
					<Switch
						checkedChildren="开启"
						unCheckedChildren="关闭"
						size="large"
						checked={text == 1}
						onClick={e => handleSwitch(e, record, "isSync")}
					/>
				);
			}
		},
		{
			title: "操作",
			code: "id",
			width: 250,
			lock: true,
			render: (_, record) => (
				<div className="opera-span-common" style={{ display: "felx", alignItems: "center" }}>
					{record.storeState != 1 ? (
						<>
							<Button type="link" onClick={() => handleClick(record.type, record.id)} key="6">
								重新授权
							</Button>
						</>
					) : (
						<Button type="link" onClick={() => handleEdit(record)}>
							编辑
						</Button>
					)}
					<Dropdown
						trigger="hover"
						overlay={
							<Menu>
								<Menu.Item
									onClick={() => {
										setVisible("mpdifyRecords");
										setRecordData(record);
									}}
									key="1"
								>
									修改记录
								</Menu.Item>
								<Menu.Item
									onClick={() => {
										groupConfig(record);
										setRecordData(record);
									}}
									key="2"
								>
									店铺分组
								</Menu.Item>
								<Menu.Item
									onClick={() => {
										handleStoreTag(record);
									}}
									key="4"
								>
									网店标签
								</Menu.Item>

								{record.storeState == 3 ? (
									<Menu.Item key="5">
										<Popconfirm title="确定删除?" onConfirm={() => handleDelete(record)} okText="确定" cancelText="取消">
											<span>删除</span>
										</Popconfirm>
									</Menu.Item>
								) : (
									<Menu.Item
										onClick={() => {
											setVisible("close");
											setRecordData(record);
										}}
										key="3"
									>
										关闭店铺
									</Menu.Item>
								)}
							</Menu>
						}
					>
						<Button type="link">
							更多
							<DownOutlined />
						</Button>
					</Dropdown>
				</div>
			)
		}
	];

	useImperativeHandle(ref, () => ({
		tableList: data,
		exportParams: stageParams,
		selectRowKeys,
		recordData
	}));

	useEffect(() => {
		setPagination({
			...(pagination || initPagination),
			current: 1
		});
	}, [query, updateKey]);

	useEffect(() => {
		if (pagination) {
			getTableListFunc();
		}
	}, [pagination]);

	//获取列表数据
	const getTableListFunc = async () => {
		setLoading(true);
		const params = {
			...query,
			size: pagination.pageSize,
			current: pagination.current
		};
		if (params.authTime) {
			params.authStartTime = moment(params.authTime[0]._d).format(dateFormat);
			params.authEndTime = moment(params.authTime[1]._d).format(dateFormat);
		}
		if (params.authExpireTime) {
			params.authStartExpireTime = moment(params.authExpireTime[0]._d).format(dateFormat);
			params.authEndExpireTime = moment(params.authExpireTime[1]._d).format(dateFormat);
		}
		params.authTime = undefined;
		params.authExpireTime = undefined;
		stageParams.current = params;
		const { data, success } = await getTableDataOp(params);
		if (success) {
			const { records = [], total = 0 } = data || {};
			pagination.total = total;
			setData(records);
		}
		setLoading(false);
	};

	//切换开关
	const handleSwitch = async (e, record, code) => {
		setLoading(true);
		const { success, msg } = await operateSevice[code]({ [code]: e ? 1 : 0, storePk: record.id });
		if (success) {
			message.success(msg);
			setPagination({ ...pagination });
		}
		setLoading(false);
	};

	//切换同步开关
	const handleAsyncSwitch = async val => {
		setLoading(true);
		const { success, msg } = await updateSyncStockStatus({
			...val,
			isSyncStock: inventoryType ? 1 : 0,
			storePk: recordData.id
		});
		if (success) {
			message.success(msg);
			setPagination({ ...pagination });
			setVisible(false);
			setRecordData({});
			setinventoryType(false);
		}
		setLoading(false);
	};

	//同步库存开关
	const handleAsyncInventory = (e, record) => {
		setRecordData({ ...record });
		setVisible("inventory");
		setinventoryType(e);
	};

	//删除操作
	const handleDelete = async record => {
		setLoading(true);
		const { data, success } = await deleteEcStoreOp({ id: record.id });
		if (success) {
			message.success("删除成功");
			setPagination({ ...pagination, current: 1 });
		}
		setLoading(false);
	};

	//网店标签
	const handleStoreTag = record => {
		setRecordData(record);
		setVisible("storeTag");
	};

	//编辑操作店铺设置
	const handleEdit = record => {
		setVisible("editStore");
		setRecordData(record);
	};

	//关闭店铺
	const closeShop = async () => {
		setLoading(true);
		const { success } = await storeAuthClosed({
			id: recordData.id
		});
		setLoading(false);
		if (success) {
			message.success("关闭成功");
			setVisible(false);
			setRecordData({});
			setPagination({
				...(pagination || initPagination),
				current: 1
			});
		}
	};

	//关闭授权店铺提示
	const CloseStoreModalProps = {
		visible: visible == "close",
		handleCancel() {
			setVisible(false);
			setRecordData({});
		},
		handleOk() {
			closeShop();
		}
	};

	//店铺设置修改记录
	const ModifyRecordModalProps = {
		visible: visible == "mpdifyRecords",
		recordData,
		handleCancel() {
			setVisible(false);
			setRecordData({});
		}
	};

	//编辑网店标签
	const SetPickLabelModalProps = {
		item: recordData,
		visible: visible == "storeTag",
		handleOk() {
			setVisible(false);
			setPagination({ ...pagination, current: 1 });
			setRecordData({});
		},
		handleCancel() {
			setVisible(false);
			setRecordData({});
		}
	};

	//店铺编辑设置
	const StoreSettingModalProps = {
		recordData,
		visible: visible == "editStore",
		type: "edit",
		handleOk() {
			setVisible(false);
			setPagination({ ...pagination, current: 1 });
			setRecordData({});
		},
		handleCancel() {
			setVisible(false);
			setRecordData({});
		}
	};

	//库存修改提示
	const InventoryTipModalProps = {
		visible: visible == "inventory",
		item: recordData,
		inventoryType,
		handleCancel() {
			setVisible(false);
			setRecordData({});
			setinventoryType(false);
		},
		handleOk(val) {
			handleAsyncSwitch(val);
		}
	};


	//表格组件
	const TableRenderProps = {
		data,
    rowKey: 'id',
    columns,
    style: {
      height: `calc(100vh - ${headerHeight + 224}px)`
    },
    checkOption: {
      value: selectRowKeys,
      onChange(val) {
				setSelectRowKeys(val);
      }
    },
    pageConfig: {
      pages: pagination,
      selectTotal: selectRowKeys.length,
      handlePageSize(page, size) {
        setPagination({
          ...pagination,
          current: page,
          pageSize: size
        });
      }
    }
	}

	return (
		<>
			<TableRender {...TableRenderProps} />
			<ModifyRecordModal {...ModifyRecordModalProps} />
			<SetPickLabelModal {...SetPickLabelModalProps} />
			{visible == "editStore" ? <StoreSettingModal {...StoreSettingModalProps} /> : ""}
			<CloseStoreModal {...CloseStoreModalProps} />
			<InventoryTipModal {...InventoryTipModalProps} />
			<CommonLoading loading={loading} />
		</>
	);
};

export default forwardRef(TableContent);
